package controller


import (
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
	"github.com/dgrijalva/jwt-go"
	//"log"
    "github.com/gomodule/redigo/redis"
	"root/utility"
	"fmt"
	"crypto/md5"
	//"encoding/hex"
	//"reflect"
	//"github.com/jinzhu/gorm"
	//"database/sql"
	//"time"
	"root/consts"
	"root/model"
)



func Register(c *gin.Context)  {

	mobile 		:= c.PostForm("mobile")
	code 		:= c.PostForm("code")
	password 	:= c.PostForm("password")
	//invate_code := c.PostForm("invate_code")
	ip 			:= c.PostForm("ip")
	if mobile == ""{
		SendResponse(c,400,"手机号不能为空",nil)
		return
	}
	if code == ""{
		SendResponse(c,400,"验证码不能为空",nil)
		return
	}
	if password == ""{
		SendResponse(c,400,"密码不能为空",nil)
		return
	}
	if ip == ""{
		SendResponse(c,400,"IP不能为空",nil)
		return
	}

	conn := utility.GetRedisConn()
	defer conn.Close()

	scode, err := redis.String(conn.Do("GET",consts.GetloginPhoneCodeKey(mobile)))
	//fmt.Print(err)
	if err != nil {
		SendResponse(c, 400, "该手机号并未获得验证码",err)
		return
	}
	//fmt.Printf("uid:%s", c.MustGet("uid"))
	if scode != code  {
		SendResponse(c, 400, "验证码错误",nil)
		return
	}

	//检测手机号是否注册
	db :=utility.GetDb()
	user := model.User{}
	res  := db.Where("mobile = ?", mobile).First(&user)
	if res.RowsAffected >= 1 {
		SendResponse(c, 400, "用户已存在",nil)
		return
	}

	//保存数据
	add := model.User{Mobile: mobile, Password: Md5(password), InvateCode: "1234"}
	res1 := db.Create(&add) // 通过数据的指针来创建
	if(res1.RowsAffected <= 0){
		SendResponse(c, 400, "注册失败",nil)
		return
	}
	//生成token
	custom := utility.CustomClaims{

		add.Id,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(consts.TokenExpireDuration).Unix(), // 过期时间
			Issuer:    "my-project",                               // 签发人
		},
	}


	//获取token
	Jwt := utility.NewJWT()
	token ,_:= Jwt.CreateToken(custom)
	SendResponse(c, 200, "ok",token)
	//conn := utility.GetRedisConn()
	//defer conn.Close()
	//
	//data, err := redis.String(conn.Do("GET", "username"))
	//if err != nil {
	//	log.Println(err)
	//	return
	//}
	//
	////c.Get("claims")
	//
	//a := c.MustGet("claims")
	//
	////val := reflect.ValueOf(a)
	////typ := reflect.Indirect(val).Type()
	//fmt.Print(a["aud"])

	//c.String(200, data)

}


func Login(c *gin.Context)  {

	var param model.User
	if err := c.ShouldBind(&param); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return

	}

	mobile 		:= c.PostForm("mobile")
	password 	:= c.PostForm("password")
	ip 			:= c.PostForm("ip")
	if mobile == ""{
		SendResponse(c,400,"手机号不能为空",nil)
		return
	}
	if password == ""{
		SendResponse(c,400,"密码不能为空",nil)
		return
	}
	if ip == ""{
		SendResponse(c,400,"IP不能为空",nil)
		return
	}

	db :=utility.GetDb()
	user := model.User{}
	res  := db.Where("mobile = ?", mobile).First(&user)
	if res.RowsAffected <= 0 {

		SendResponse(c, 1010, "",nil)
		return
	}
	data := []byte(password)
	md5str := fmt.Sprintf("%x", md5.Sum(data))
	if user.Password != md5str{
		SendResponse(c,1011,"",nil)
		return
	}
	if user.State == 2 {
		SendResponse(c,1012,"",nil)
		return
	}

	custom := utility.CustomClaims{

		user.Id,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(consts.TokenExpireDuration).Unix(), // 过期时间
			Issuer:    "my-project",                               // 签发人
		},
	}


	//获取token
	Jwt := utility.NewJWT()
	token ,_:= Jwt.CreateToken(custom)

	SendResponse(c,200,"",token)
}

func SendCode(c *gin.Context)  {
	utility.Send("139",123456)
}

func Md5(str string ) string {
	data := []byte(str)
	md5str := fmt.Sprintf("%x", md5.Sum(data))
	return md5str
}
